function ﻿$(id){
	if(typeof(id) == "string"){
		return document.getElementById(id);
	}else{
		return id;
	}
}
//获取XMLHttpObject对象
function GetXmlHttpObject(){
	var xmlHttp=null;
	try { 
		xmlHttp=new XMLHttpRequest();
		 }catch (e) {
		 	 try { 
		 	 	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); 
		 	 	} catch (e) {
		 	 		 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); 
		 	 		 } 
		 	 		 }
	return xmlHttp;
}

var XHRUpload = function(jsonMap){
				this.config = { url:null, name:null, element:null, size:3000000, formate:/./ }  //配置变量
				this.files = [];    //文件列表
				this.index = 0;     //文件索引
				this.mix(this.config, jsonMap); //赋值.
				this.init(jsonMap);     //初使化
		}
//prototype 返回对象原型...
XHRUpload.prototype = {
//初使化
	init:function(jsonMap){
		var self = this;
		var element = jsonMap.element;
		element.addEventListener("dragenter", this._stopPrevent, false);
		element.addEventListener("dragover", this._stopPrevent, false);
		element.addEventListener("drop", function(e){ e.stopPropagation(); e.preventDefault(); self.start(e);   }, false);
	},
	//阻止浏览器默认动作 和事件冒泡
	_stopPrevent:function(e){
		 e.stopPropagation();
		 e.preventDefault(); 
	},
	//赋值.给config赋值
	mix:function(a, b){
		 for(var i in b){
		 	 a[i] = b[i];
		  } 
		return a; 
	},
	//消息.处理
	onMsg:function(msg){
		
	},
	//开始上传
	start:function(e){
		console.log(e);
		// 拖拽可以在event.dataTransfer 中获取file对象
		if(e.dataTransfer.files.length == 0){return false}; //如果没有.返回false
		this.index--;
		this.files = this.files.concat( [].slice.call(e.dataTransfer.files) );
		this.next(); // 上传下一个
	},
//上传下一个文件
	next:function(){
		var self = this;
		if(self.files.length > ++self.index ){
			var file = self.files[self.index];
			self.onMsg('开始上传第 ' + (self.index+1) + ' 个文件!');    //记录消息.
			
			if(file.type.indexOf('image') != -1){
				var img_reader = new FileReader();
				img_reader.onload = (function (theFile) { return function (e) {
				obj_ImgData = e.target.result;
				create_Img({Name:'Img_'+self.index+1, Src:e.target.result, Title:theFile.name});
				}; })(file)
				img_reader.readAsDataURL(file);
			}
			
			self.reader(file, self.upload);
		}
	},
	//标准方法读取文件2进制数据.文件.上传函数
	reader:function(file, callBack){
		var self = this;
		console.log(file);
		if(!self.checkFormate(file)){
			//记录消息..
			self.onMsg('<span style="color:#FF0000">第 ' + (self.index+1) + ' 个文件 ' + file.name + ' 貌似不是图片文件的说.!</span>');
			self.next();
			return false;
		}
		if (!self.checkFormsize(file))
		{
		var fsize = Math.floor((file.size/1024)/1024);
		self.onMsg('<span style="color:#FF0000">第 ' + (self.index+1) + ' 个文件 ' + file.name + ' 貌似有点大(' + fsize + ' M) 最大只能(2M).!</span>');
		self.next();
		return false;
		}
		var fileReader = new FileReader();
		fileReader.onloadend = function(){
		callBack.call(self, fileReader, file.name, file.FileSize);
		}
		fileReader.onerror = function(e)
		{
		self.onMsg('<span style="color:#FF0000">读取第 ' + (self.index+1) + ' 个文件时出错!</span>');    //记录消息.
		self.next();
		}
		fileReader.readAsBinaryString(file);// 开始读取2进制数据 异步 参数为file 对象
	},
	//清除上传队列中的文件
	remove:function(index){
		 return this.files.splice(index, 1); 
	},
	//添加.
	add:function(file){ 
		if(file instanceof File){   
			return this.files.push(file) 
		} 
		return false;
	 },
	// 停止当前上传的文件
	abort:function(){ 
		this.XHR.abort();
	 },
//上传.
	upload:function(fileReader, fileName, fileSize){
		console.log(fileReader) //输出?
		var self = this;
		
		//var data = this.getBuild({fileName:fileName, binary:fileReader.result});  //获取数据.
		
		this.XHR = GetXmlHttpObject();
		this.XHR.onerror = function(msg){self.next(); self.onMsg(msg); };       //错误记录
		this.XHR.onuploadprogress = self.onMsg;         //进度回调
		this.XHR.onreadystatechange = function(){//上传状态改变回调
			var jd = (100/4)*(self.XHR.readyState);
			self.onMsg('当前已经上传了: '+jd+'%');
			if (self.XHR.readyState == 4 || self.XHR.readyState == "complete"){
				console.log(self.XHR);
				var rCon = self.XHR.responseText;
				if(rCon == '上传失败!' || rCon == ''){
					self.onMsg('<span style="color:#F00">第 ' + (self.index+1) + ' 个文件' + fileName + ' 上传失败!</span>');
					$('Img_'+self.index+1).style.border = '3px solid #FF0000';
				}else{
					self.onMsg('<span style="color:#0F0">第 ' + (self.index+1) + ' 个文件' + fileName + ' ' + rCon + '.</span>');
					$('Img_'+self.index+1).style.border = '1px solid #0F0';
				}
				self.next();        //下一个
			}
		};
		this.XHR.open("POST", this.config.url, true);
		
		//this.XHR.setRequestHeader("Content-type", "multipart/form-data; boundary=" + data.boundary);  //火狐下有交接.chrome无效
		//this.XHR.overrideMimeType("text/plain; charset=x-user-defined-binary");
		
		//this.XHR.setRequestHeader("Content-type","application/x-www-form-urlencoded");
		
		if(this.XHR.sendAsBinary){
			console.log("this.XHR.sendAsBinary");
		//this.XHR.sendAsBinary(data.builder);  //FF上传方式
			this.XHR.sendAsBinary('chromeFile=' + encodeURIComponent(obj_ImgData));
		}else{
			console.log("send");
			//this.XHR.send(data.builder);
			this.XHR.send('chromeFile=' + encodeURIComponent(obj_ImgData));
		}
	},
	//获取上传数据
	getBuild:function(o){
		var boundary = '-----------------' + (new Date).getTime();
		var dashdash = '--';
		var crlf     = '\r\n';
		var builder = '';
		builder += dashdash+boundary+crlf;
		builder += 'Content-Disposition: form-data; name="'+ this.config.name +'"; filename="' + encodeURIComponent(o.fileName) + '"'+ crlf;
		builder += 'Content-Type: application/octet-stream'+ crlf + crlf;
		/* 二进制数据 */
		builder += o.binary + crlf;
		builder += dashdash + boundary + dashdash + crlf;
		
		return { boundary : boundary, builder : builder };
	},
	//验证用户拖入的文件类型
	checkFormate:function(file){
		console.log(file.fileName,file.name);
		 return this.config.formate.test(file.name)
	},
	//验证文件大小
	checkFormsize:function(file){ 
		return (this.config.size > file.size) 
	},
}
var obj_ImgData = '';           //图片变量
//创建图片对象.并显示
var create_Img = function(img){
	var obj_img = document.createElement("img");
	obj_img.id = img.Name || 'obj_Img';
	obj_img.style.margin = '5px';
	obj_img.style.maxWidth = '100px';
	obj_img.style.maxHeight = '100px';
	obj_img.style.cursor = 'pointer';
	obj_img.style.border = '2px solid #FFCC00';
	obj_img.title = img.Title || 'Image';
	
	obj_img.src = img.src || obj_ImgData;
	obj_img.onclick = function(){window.open(obj_img.src);};
	
	$('div_img').appendChild(obj_img);

}